const tronWeb = require('./tronweb')
const config = require('./config')
const utils = require('./utils')

const CID = config.contractId
let lastEnergyUsed = 0
let contract
let color = 0xff0000
let interval = 5 * 1000

const colors = ['0000ff', '000000', 'ffff00', '00ff00', 'ff0000']

function randomShape() {
  let rndCoo = Math.floor(Math.random() * 998 * 998 + 101)
  let rndColIndex = Math.floor((Math.random() * 100) % colors.length) 
  let rndCol = parseInt(colors[rndColIndex], 16)
  return [
    rndCoo, rndCol,
    rndCoo-1, rndCol,
    rndCoo+1, rndCol,
    rndCoo-1000, rndCol,
    rndCoo + 1000, rndCol
  ]
}

async function getPixelsPrice(pixels) {
  let coordinates = []
  for (let i = 0; i < pixels.length; i += 2) {
    coordinates.push(pixels[i])
  }
  let result = await contract.getTotalPrice(coordinates).call()
  console.log('get pixels price:', result)
  return result.totalPrice.toString()
}

async function buyPixel() {
  let pixels = randomShape()
  try {
    let price = await getPixelsPrice(pixels)
    const args = {
      // shouldPollResponse: true,
      callValue: price,
    }
    let r = await contract.buyPixels(pixels).send(args)
    console.log('buy pixels:', pixels, r)
    // if (Number(r) > 0) {
    //   console.log('buy pixel success:', r, coordinate, color)
    // } else {
    //   console.log('buy pixel failed:', r, coordinate, color)
    // }
    r = await tronWeb.trx.getAccountResources()
    let energyUsed = Number(r.EnergyUsed)
    if (lastEnergyUsed > 0) {
      console.log('energy used: %d, total used: %d, limit: %d', energyUsed - lastEnergyUsed, energyUsed, r.EnergyLimit)
    }
    lastEnergyUsed = energyUsed
  } catch (e) {
    console.log('buy pixel failed:', e)
  }
}

async function main() {
  contract = await tronWeb.contract().at(CID)
  utils.loopAsync(buyPixel, interval)
}

main().then().catch(console.log)
